using System.Net.WebSockets;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace Native.WebSocket.Controllers;

[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    [HttpGet]
    public async Task Index()
    {
        if (HttpContext.WebSockets.IsWebSocketRequest)
        {
            using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
            await WsHandler(webSocket);
        }
        else
        {
            HttpContext.Response.StatusCode = 400;
        }
    }

    private async Task WsHandler(System.Net.WebSockets.WebSocket ws)
    {
        var buffer = new byte[1024 * 4];
        var receive = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        while (!receive.CloseStatus.HasValue) //EOF
        {
            var msg = Encoding.UTF8.GetString(buffer, 0, receive.Count);
            Console.WriteLine($"收到消息: {msg}");
            
            await ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg)),
                receive.MessageType,
                receive.EndOfMessage,
                CancellationToken.None);

            receive = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        }

        await ws.CloseAsync(receive.CloseStatus.Value, receive.CloseStatusDescription, CancellationToken.None);
    }
}